import com.googlecode.lightest.studio.CommonConstraints
import com.googlecode.lightest.studio.Test
import com.googlecode.lightest.studio.TestDirectory

class TestDirectoryController {

    def scaffold = TestDirectory

    def testReaderService
    def testCopierService

    def refresh = {
        def dirs = TestDirectory.list()

        dirs.each {
            // refresh suite listing here
        }
    }

    def scan = {}

    /**
     * Scans the given directory for test files, saving any it finds.
     */
    def handleScan = { HandleScanCommand cmd ->
        if (cmd.hasErrors()) {
            flash.message = cmd.errors.toString()
            redirect(action: 'scan')
        }

        def tests
        def dir = new File(cmd.dir)

        try {
            def classLoader = new GroovyClassLoader(this.class.classLoader)  // TODO - get the right class loader
            tests = testReaderService.readDir(dir, classLoader)
        }
        catch (e) {
            flash.message = "Exception reading tests from ${dir}: ${e}"
            redirect(action: 'scan')
        }

        def notCopied = testCopierService.copyAll(tests)

        notCopied.each { test ->
            flash.message += test.errors.toString()  // TODO - make more robust
        }

        redirect(controller: 'test')
    }
}


/**
 * A Command Object for the scan action.
 */
class HandleScanCommand {
    String dir

    static constraints = {
        dir (blank: false, validator: { return CommonConstraints.dirOk(it) })
    }
}
